<template>
  <div class="publish-activity">
    <div class="page-header">
      <h2>发布活动</h2>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="activity-form"
    >
      <el-form-item label="活动名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入活动名称" />
      </el-form-item>

      <el-form-item label="活动描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入活动描述"
        />
      </el-form-item>

      <el-form-item label="活动时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="defaultTime"
        />
      </el-form-item>

      <el-form-item label="活动地点" prop="location">
        <el-input v-model="form.location" placeholder="请输入活动地点" />
      </el-form-item>

      <el-form-item label="报名人数" prop="maxEnroll">
        <el-input-number
          v-model="form.maxEnroll"
          :min="1"
          :max="1000"
          placeholder="请输入最大报名人数"
        />
      </el-form-item>

      <el-form-item label="报名截止" prop="enrollDeadline">
        <el-date-picker
          v-model="form.enrollDeadline"
          type="datetime"
          placeholder="请选择报名截止时间"
          :default-time="defaultTime[0]"
        />
      </el-form-item>

      <el-form-item label="活动类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择活动类型">
          <el-option label="文体活动" value="SPORTS" />
          <el-option label="学术讲座" value="ACADEMIC" />
          <el-option label="志愿服务" value="VOLUNTEER" />
          <el-option label="文化交流" value="CULTURE" />
          <el-option label="其他" value="OTHER" />
        </el-select>
      </el-form-item>

      <el-form-item label="活动标签">
        <el-tag
          v-for="tag in form.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
          class="tag-item"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          class="tag-input"
          size="small"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">
          + 添加标签
        </el-button>
      </el-form-item>

      <el-form-item label="活动封面">
        <el-upload
          class="cover-uploader"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
        >
          <img v-if="form.coverUrl" :src="form.coverUrl" class="cover" />
          <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">发布活动</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const router = useRouter()
const formRef = ref()

// 表单数据
const form = ref({
  title: '',
  description: '',
  time: [],
  location: '',
  maxEnroll: 50,
  enrollDeadline: '',
  type: '',
  tags: [],
  coverUrl: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请选择活动时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && value[0] && value[1]) {
          if (dayjs(value[0]).isBefore(dayjs())) {
            callback(new Error('开始时间不能早于当前时间'))
          } else if (dayjs(value[1]).isBefore(value[0])) {
            callback(new Error('结束时间不能早于开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxEnroll: [
    { required: true, message: '请输入最大报名人数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 1) {
          callback(new Error('报名人数必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  enrollDeadline: [
    { required: true, message: '请选择报名截止时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.value.time && form.value.time[0]) {
          if (dayjs(value).isBefore(dayjs())) {
            callback(new Error('报名截止时间不能早于当前时间'))
          } else if (dayjs(value).isAfter(form.value.time[0])) {
            callback(new Error('报名截止时间不能晚于活动开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ]
}

// 默认时间
const defaultTime = [
  new Date(2000, 1, 1, 8, 0, 0),
  new Date(2000, 1, 1, 18, 0, 0)
]

// 标签相关
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref()

const handleClose = (tag) => {
  form.value.tags = form.value.tags.filter(t => t !== tag)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (form.value.tags.length >= 5) {
      ElMessage.warning('最多添加5个标签')
      return
    }
    if (!form.value.tags.includes(inputValue.value)) {
      form.value.tags.push(inputValue.value)
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 封面上传相关
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传封面图片只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传封面图片大小不能超过 2MB!')
  }

  return isImage && isLt2M
}

const handleCoverSuccess = (res) => {
  form.value.coverUrl = res.data.url
  ElMessage.success('封面上传成功')
}

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const activityData = {
          ...form.value,
          startTime: form.value.time[0],
          endTime: form.value.time[1]
        }
        delete activityData.time

        const response = await fetch('/api/club/activities', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(activityData)
        })

        if (response.ok) {
          ElMessage.success('活动发布成功')
          router.push('/club/manage')
        } else {
          throw new Error('发布失败')
        }
      } catch (error) {
        console.error('发布活动失败：', error)
        ElMessage.error('发布活动失败')
      }
    } else {
      console.log('表单验证失败：', fields)
    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  form.value.tags = []
  form.value.coverUrl = ''
}
</script>

<style lang="scss" scoped>
.publish-activity {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .activity-form {
    max-width: 800px;
    margin: 0 auto;

    .tag-item {
      margin-right: 8px;
      margin-bottom: 8px;
    }

    .tag-input {
      width: 90px;
      margin-right: 8px;
      vertical-align: bottom;
    }

    .button-new-tag {
      margin-bottom: 8px;
    }

    .cover-uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
          border-color: var(--el-color-primary);
        }
      }

      .cover-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
        line-height: 178px;
      }

      .cover {
        width: 178px;
        height: 178px;
        display: block;
        object-fit: cover;
      }
    }
  }
}
</style> 